import { useState, useReducer } from "react"
import { produce } from "immer"
function reducer(state, action) {
    switch (action.type) {
        case 'add':
            // return {
            //     result: state.result + action.num
            // }
            return produce(state, (state) => {
                state.result += action.num
            })//配合immer使用
        // state.result=state.result+action.num 不能这样写
        case 'minus':
            return {
                result: state.result - action.num
            }
    }
}
function App() {
    //useReducer接收的第二个参数作为reducer的第一个参数
    //dispatch接收的参数作为reducer的第二个参数
    const [res, dispatch] = useReducer(reducer, { result: 0 })
    return (
        <div>
            <h3>{res.result}</h3>
            <button onClick={() => dispatch({ typeminus: 'add', num: 2 })}>+</button>
            <button onClick={() => dispatch({ type: 'minus', num: 1 })}>-</button>
        </div>
    )
}

export default App;